<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据导入 - 新页面</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .glass-effect {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen flex items-center justify-center p-4">
        <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl transform transition-all duration-300">

            <!-- 头部 -->
            <div class="bg-gradient-to-r from-blue-500 to-purple-600 text-white p-6 rounded-t-2xl">
                <div class="flex justify-between items-center">
                    <h2 class="text-2xl font-bold">
                        <i class="fas fa-upload mr-2"></i>数据导入
                    </h2>
                    <button onclick="window.close()" class="text-white hover:text-gray-200 text-2xl">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <p class="text-blue-100 mt-2">在新窗口中完成数据导入操作</p>
            </div>

            <!-- 内容区域 -->
            <div class="p-8">
                <form id="importForm" class="space-y-6">
                    <!-- 数据表名称 -->
                    <div>
                        <label for="table-name" class="block text-sm font-medium text-gray-700 mb-2">
                            数据表名称 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" id="table-name" required 
                               class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="请输入数据表名称">
                    </div>

                    <!-- 平台选择 -->
                    <div>
                        <label for="platform" class="block text-sm font-medium text-gray-700 mb-2">
                            平台 <span class="text-red-500">*</span>
                        </label>
                        <select id="platform" required 
                                class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">请选择平台</option>
                        </select>
                    </div>

                    <!-- 店铺选择 -->
                    <div>
                        <label for="store" class="block text-sm font-medium text-gray-700 mb-2">
                            店铺 <span class="text-red-500">*</span>
                        </label>
                        <select id="store" required 
                                class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">请先选择平台</option>
                        </select>
                    </div>

                    <!-- 时间范围 -->
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label for="start-date" class="block text-sm font-medium text-gray-700 mb-2">
                                开始时间 <span class="text-red-500">*</span>
                            </label>
                            <input type="date" id="start-date" required 
                                   class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                        <div>
                            <label for="end-date" class="block text-sm font-medium text-gray-700 mb-2">
                                结束时间 <span class="text-red-500">*</span>
                            </label>
                            <input type="date" id="end-date" required 
                                   class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        </div>
                    </div>

                    <!-- 文件上传 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">选择文件 <span class="text-red-500">*</span></label>
                        <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors cursor-pointer"
                             onclick="document.getElementById('file-upload').click()">
                            <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
                            <p class="text-gray-600 mb-2">点击或拖拽文件到此处上传</p>
                            <p class="text-sm text-gray-500">支持 CSV、Excel 文件</p>
                            <input type="file" id="file-upload" accept=".csv,.xlsx,.xls" required class="hidden">
                        </div>
                        <div id="file-info" class="hidden mt-3 p-3 bg-blue-50 rounded-lg">
                            <div class="flex justify-between items-center">
                                <span id="file-name" class="text-sm text-blue-700"></span>
                                <button type="button" id="remove-file" class="text-red-500 hover:text-red-700">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 导入规则 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">导入规则</label>
                        <div class="space-y-2">
                            <label class="flex items-center">
                                <input type="checkbox" id="overwrite" class="mr-2">
                                <span class="text-sm">覆盖已有数据</span>
                            </label>
                            <label class="flex items-center">
                                <input type="checkbox" id="validate" class="mr-2" checked>
                                <span class="text-sm">数据验证</span>
                            </label>
                        </div>
                    </div>

                    <!-- 进度条 -->
                    <div id="import-progress" class="hidden">
                        <div class="bg-gray-200 rounded-full h-2">
                            <div id="progress-bar" class="bg-blue-600 h-2 rounded-full transition-all duration-300" style="width: 0%"></div>
                        </div>
                        <p id="progress-text" class="text-sm text-gray-600 mt-2 text-center">0%</p>
                    </div>

                    <!-- 按钮区域 -->
                    <div class="flex justify-end space-x-4 pt-6 border-t">
                        <button type="button" onclick="window.close()" 
                                class="px-6 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                            取消
                        </button>
                        <button type="submit" id="submit-btn"
                                class="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50">
                            开始导入
                        </button>
                    </div>
                </form>
            </div>


        </div>
    </div>

    <script>
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', () => {
            loadPlatforms();
            setDefaultDates();
            setupFileUpload();
        });

        // 设置默认日期
        function setDefaultDates() {
            const today = new Date();
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            
            document.getElementById('end-date').value = today.toISOString().split('T')[0];
            document.getElementById('start-date').value = yesterday.toISOString().split('T')[0];
        }

        // 加载平台数据
        async function loadPlatforms() {
            try {
                const response = await fetch('/api/platforms');
                const platforms = await response.json();
                
                const platformSelect = document.getElementById('platform');
                platformSelect.innerHTML = '<option value="">请选择平台</option>';
                
                platforms.forEach(platform => {
                    const option = document.createElement('option');
                    option.value = platform.plat_id;
                    option.textContent = platform.plat_name;
                    platformSelect.appendChild(option);
                });
                
                // 绑定平台变化事件
                platformSelect.addEventListener('change', handlePlatformChange);
                
            } catch (error) {
                console.error('加载平台数据失败:', error);
                alert('加载平台数据失败，请刷新页面重试');
            }
        }

        // 处理平台选择变化
        async function handlePlatformChange(event) {
            const selectedPlatform = event.target.value;
            const storeSelect = document.getElementById('store');
            
            if (selectedPlatform) {
                try {
                    const response = await fetch(`/api/stores/${encodeURIComponent(selectedPlatform)}`);
                    const stores = await response.json();
                    
                    storeSelect.innerHTML = '<option value="">请选择店铺（可选）</option>';
                    stores.forEach(store => {
                        const option = document.createElement('option');
                        option.value = store.shop_id;
                        option.textContent = store.shop_name;
                        storeSelect.appendChild(option);
                    });
                } catch (error) {
                    console.error('加载店铺数据失败:', error);
                    storeSelect.innerHTML = '<option value="">加载失败</option>';
                }
            } else {
                storeSelect.innerHTML = '<option value="">请先选择平台（可选）</option>';
            }
        }

        // 设置文件上传
        function setupFileUpload() {
            const fileUpload = document.getElementById('file-upload');
            const fileInfo = document.getElementById('file-info');
            const fileName = document.getElementById('file-name');
            const removeFile = document.getElementById('remove-file');

            fileUpload.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    fileName.textContent = file.name;
                    fileInfo.classList.remove('hidden');
                }
            });

            removeFile.addEventListener('click', () => {
                fileUpload.value = '';
                fileInfo.classList.add('hidden');
            });

            // 拖拽上传
            const uploadArea = document.querySelector('.border-2.border-dashed');
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('border-blue-400', 'bg-blue-50');
            });

            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('border-blue-400', 'bg-blue-50');
            });

            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('border-blue-400', 'bg-blue-50');
                
                const file = e.dataTransfer.files[0];
                if (file && (file.type === 'text/csv' || file.type.includes('spreadsheet') || file.name.endsWith('.xlsx') || file.name.endsWith('.xls'))) {
                    fileUpload.files = e.dataTransfer.files;
                    fileName.textContent = file.name;
                    fileInfo.classList.remove('hidden');
                }
            });
        }
        

        // 表单提交处理
        document.getElementById('importForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const submitBtn = document.getElementById('submit-btn');
            const progressDiv = document.getElementById('import-progress');
            const progressBar = document.getElementById('progress-bar');
            const progressText = document.getElementById('progress-text');

            // 验证表单
            const tableName = document.getElementById('table-name').value;
            const startDate = document.getElementById('start-date').value;
            const endDate = document.getElementById('end-date').value;
            const file = document.getElementById('file-upload').files[0];

            if (!tableName || !startDate || !endDate || !file) {
                alert('请填写所有必填项');
                submitBtn.disabled = false;
                return;
            }

            // 显示进度条
            submitBtn.disabled = true;
            progressDiv.classList.remove('hidden');

            // 模拟导入进度
            let progress = 0;
            const interval = setInterval(() => {
                progress += Math.random() * 15;
                if (progress > 100) progress = 100;
                
                progressBar.style.width = progress + '%';
                progressText.textContent = Math.round(progress) + '%';

                if (progress >= 100) {
                    clearInterval(interval);
                    setTimeout(() => {
                        alert('导入成功！\n\n文件已成功上传到服务器，正在处理数据...');
                        
                        // 可以选择关闭窗口或重置表单
                        if (confirm('是否关闭当前窗口？')) {
                            window.close();
                        } else {
                            // 重置表单
                            document.getElementById('importForm').reset();
                            document.getElementById('file-info').classList.add('hidden');
                            submitBtn.disabled = false;
                            progressDiv.classList.add('hidden');
                        }
                    }, 1000);
                }
            }, 300);
        });
    </script>
</body>
</html>